package cn.itcast.myapplication.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import cn.itcast.myapplication.R;
import cn.itcast.myapplication.adapter.WordAdapter;
import cn.itcast.myapplication.viewemodel.WordViewModel;
import cn.itcast.myapplication.room.Word;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;

import java.util.List;
public class RoomBasic extends AppCompatActivity {

    private WordViewModel wordViewModel;
    private RecyclerView recyclerView;
    private WordAdapter wordAdapter1,wordAdapter2;
    boolean useSwitch;
    private AlertDialog alertDialog;
    private TextView textView;
    private LiveData<List<Word>> filteradWords;
    private SearchView searchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_room_basic);

        wordViewModel=new ViewModelProvider(this).get(WordViewModel.class);//创建ViewModel对象

        initView();//初始化

        //通过LiveData获取数据列表,可以监听数据的变化，不需要在增删改查里面再去声明
        wordViewModel.getAllWordsLive().observe(this, new Observer<List<Word>>() {

            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onChanged(List<Word> words) {

                int temp=wordAdapter1.getItemCount();

                wordAdapter1.setAllWord(words);//添加数据1

                wordAdapter2.setAllWord(words);//添加数据2

                //判断数据的长度是否有发生改变，再进行刷新，防止重复刷新引发的卡顿
                if (temp!=words.size()){

                    wordAdapter1.notifyDataSetChanged();//刷新1

                    wordAdapter2.notifyDataSetChanged();//刷新2

                }

             }

        });

    }

    //初始化
    private void initView() {

        android.widget.ImageView imageView = (ImageView) findViewById(R.id.imageView);

        textView=(TextView)findViewById(R.id.textView5);

        recyclerView=(RecyclerView)findViewById(R.id.recyclerView);//回收布局

        wordAdapter1=new WordAdapter(this,true,wordViewModel);//true 显示普通布局

        wordAdapter2=new WordAdapter(this,false,wordViewModel);//false 显示卡片布局

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.setAdapter(wordAdapter1);//设置适配器

        wordViewModel.getNumber().observe(this, new Observer<Integer>() {

            @Override
            public void onChanged(Integer integer) {

                textView.setText("词汇量"+integer);

            }

        });

        imageView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                Intent intent=new Intent(RoomBasic.this, AddActivity.class);

                startActivity(intent);

            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

          getMenuInflater().inflate(R.menu.word_menu,menu);

          SearchView searchView= (SearchView) menu.findItem(R.id.app_bar_search).getActionView();

          searchView.setMaxWidth(1000);//设置搜索输入框的宽度

          /**
           *
           * 设置文本监听
           * onQueryTextSubmit 查询文本提交
           * onQueryTextChange 查询文本变化
           *
           * */

          searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String newText) {

                return false;

            }


            @Override
            public boolean onQueryTextChange(String newText) {

                String pattern=newText.trim();//去除空格

                filteradWords=wordViewModel.findWordsWithPatten(pattern);

                filteradWords=wordViewModel.getAllWordsLive();

                filteradWords.observe(RoomBasic.this, new Observer<List<Word>>() {

                    @Override
                    public void onChanged(List<Word> words) {

                        int temp=wordAdapter1.getItemCount();

                        wordAdapter1.setAllWord(words);//添加数据1

                        wordAdapter2.setAllWord(words);//添加数据2

                        //判断数据的长度是否有发生改变，再进行刷新，防止重复刷新引发的卡顿
                        if (temp!=words.size()){

                            wordAdapter1.notifyDataSetChanged();//刷新1

                            wordAdapter2.notifyDataSetChanged();//刷新2

                        }
                    }

                });

                return true;

            }

        });


          return true;

    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()){

            case R.id.switch_view:

                if (useSwitch) {

                    useSwitch=false;

                    recyclerView.setAdapter(wordAdapter2);//卡片布局

                    item.setTitle("卡片布局");


                }else {

                    useSwitch=true;

                    recyclerView.setAdapter(wordAdapter1);//普通布局

                    item.setTitle("普通布局");

                }

                 break;

            case R.id.clear_text:

                //创建提醒对话框的建构器
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                //设置对话框的标题文本
                builder.setTitle("确定要删除所有数据吗？");
                //设置对话框的内容文本
                builder.setMessage("数据被删除后将无法恢复，请谨慎删除！！！");

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        wordViewModel.DeleteAllWord();//删除所有的数据

                    }
                });


                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        alertDialog.hide();

                    }

                });

                //设置对话框肯定文本及按钮点击事件
                //根据建构器构建提醒对话框对象
                alertDialog = builder.create();

                alertDialog.show();

            }

           return super.onOptionsItemSelected(item);

        }

    }
